package com.xywl.escort.view.coupon

import android.app.Activity
import android.content.Intent
import android.graphics.Paint
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.R
import com.xywl.escort.adapter.CouponAdapter
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.CouponBean
import com.xywl.escort.bean.CouponListResp
import com.xywl.escort.bean.MessageEvent
import com.xywl.escort.common.Constant.EventType.EVENT_MAIN_TYPE
import com.xywl.escort.widget.HorizontalDividerItemDecoration
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_coupon.*
import kotlinx.android.synthetic.main.layout_empty_view.view.*
import org.greenrobot.eventbus.EventBus
import timber.log.Timber
import javax.inject.Inject

@Route(path = "/xy/coupon")
class CouponActivity : BaseActivity(), CouponContract.View, SwipeRefreshLayout.OnRefreshListener {
    private val REQUEST_CODE_CHOOSE = 20
    private lateinit var mAdapter: CouponAdapter
    private var mList = ArrayList<CouponBean>()
    private var pageNum = 1
    private var isEnd: Boolean = false
    @Inject
    lateinit var mPresenter: CouponContract.Presenter

    @Autowired
    @JvmField
    var condMinPrice: Double = 0.0

    @Autowired
    @JvmField
    var useScene = ""

    @Autowired
    @JvmField
    var condMinDay = 0

    // 0 锦囊页面跳转进入 1 商品提交订单跳转进入 2 项目认购弹窗跳转进入
    @Autowired
    @JvmField
    var type = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_coupon)
        ARouter.getInstance().inject(this)

        initView()
        initData()
        addListener()
    }

    private fun initView() {
        showBackButton()
        setTitleText(R.string.tips_coupon)
        val manager = LinearLayoutManager(this)
        manager.orientation = LinearLayoutManager.VERTICAL
        val paint = Paint()
        paint.strokeWidth = 30f
        paint.color = ContextCompat.getColor(this, R.color.line_color)
        paint.isAntiAlias = true
        recycler_coupon.addItemDecoration(HorizontalDividerItemDecoration.Builder(this).paint(paint).build())
        recycler_coupon.layoutManager = manager

        mAdapter = CouponAdapter(R.layout.item_coupon, mList)
        recycler_coupon.adapter = mAdapter

        val emptyView = LayoutInflater.from(this).inflate(R.layout.layout_empty_view, null)
        val tvEmpty = emptyView.tv_empty
        tvEmpty.text = "暂无卡券"
        mAdapter.emptyView = emptyView

        swipeLayout.setOnRefreshListener(this)
        swipeLayout.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary, R.color.aid_prompt_color, R.color.colorBackground)
    }

    private fun initData() {
        pageNum = 1
        mPresenter.takeView(this)
        mPresenter.loadCouponList(pageNum, useScene, condMinDay, condMinPrice)
    }

    private fun addListener() {
        mAdapter.setOnLoadMoreListener({
            swipeLayout.isEnabled = false
            recycler_coupon.postDelayed({
                swipeLayout.isEnabled = false
                if (isEnd) {
                    //数据全部加载完毕
                    mAdapter.loadMoreEnd()
                    swipeLayout.isEnabled = true
                } else {
                    //成功获取更多数据
                    mPresenter.loadCouponList(pageNum, useScene, condMinDay, condMinPrice)
                }
            }, 200)
        }, recycler_coupon)

        mAdapter.setOnItemClickListener { _, _, position ->
            val coupon = mList[position]
            ARouter.getInstance().build("/xy/coupon/detail")
                    .withString("couponId", coupon.id)
                    .withInt("type", type)
                    .navigation(this, REQUEST_CODE_CHOOSE)
        }
        mAdapter.setOnItemChildClickListener { _, view, position ->
            val bean = mList[position]
            when (view.id) {
                R.id.btn_status -> {
                    // 0 锦囊页面跳转进入 1 商品提交订单跳转进入 2 项目认购跳转进入
                    when (type) {
                        0 -> {
                            val useScene = bean.useScene
                            // 1-预售项目，2-直采商品
                            when (useScene) {
                                "1" -> {
                                    EventBus.getDefault().post(MessageEvent(EVENT_MAIN_TYPE, "farm"))
                                    finish()
                                }
                                "2" -> {
                                    EventBus.getDefault().post(MessageEvent(EVENT_MAIN_TYPE, "market"))
                                    finish()
                                }
                            }
                        }
                        else -> {
                            val intent = Intent()
                            intent.putExtra("coupon", bean)
                            setResult(Activity.RESULT_OK, intent)
                            finish()
                        }
                    }
                }
                else -> {
                }
            }
        }
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun <T : Any?> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }

    override fun onRefresh() {
        mAdapter.setEnableLoadMore(false)
        pageNum = 1
        mPresenter.loadCouponList(pageNum, useScene, condMinDay, condMinPrice)
    }

    override fun updateCoupon(dataBean: CouponListResp.DataBean?) {
        swipeLayout.isRefreshing = false
        progress_bar.visibility = View.GONE
        recycler_coupon.visibility = View.VISIBLE

        if (pageNum == 1) {
            mList.clear()
        }
        mList.addAll(dataBean!!.list)
        if (pageNum >= dataBean.pages) {
            isEnd = true
        } else {
            isEnd = false
            pageNum += 1
        }
        mAdapter.setNewData(mList)
        mAdapter.loadMoreComplete()
        swipeLayout.isEnabled = true
    }

    override fun loadCouponFailure(msg: String?) {
        swipeLayout.isRefreshing = false
        progress_bar.visibility = View.GONE
        recycler_coupon.visibility = View.VISIBLE
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == Activity.RESULT_OK) {
            data?.let {
                val coupon = data.getSerializableExtra("coupon") as CouponBean
                val type = data.getIntExtra("type", -1)
                Timber.tag("CouponActivity").e("coupon=${coupon.name}")
                // 锦囊红包列表页面跳转进入 1 显示立即使用按钮页面(提交订单、认购付款弹窗页面) 2 不显示立即使用按钮(订单详情进入)
                if (type == 0) {
                    val useScene = coupon.useScene
                    // 1-预售项目，2-直采商品
                    when (useScene) {
                        "1" -> {
                            EventBus.getDefault().post(MessageEvent(EVENT_MAIN_TYPE, "farm"))
                            finish()
                        }
                        "2" -> {
                            EventBus.getDefault().post(MessageEvent(EVENT_MAIN_TYPE, "market"))
                            finish()
                        }
                    }
                } else {
                    setResult(Activity.RESULT_OK, data)
                    finish()
                }
            }
            Timber.tag("CouponActivity").e("data=$data")
        }
    }
}
